
package compilador;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.text.BadLocationException;

public class ventanaPrincipal extends javax.swing.JFrame 
{
 public ventanaPrincipal() 
    {
     sintactico=new Analisador();//se crea el objeto analisador
     initComponents();
    }
@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        compilarBoton = new javax.swing.JButton();
        limpiarBoton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        areaTextoEntrada = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        abrirMenu = new javax.swing.JMenuItem();
        guardarMenu = new javax.swing.JMenuItem();
        salirMenu = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        acercaDe = new javax.swing.JMenuItem();
        manualUsuario = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compilador del lenguaje C");
        setIconImage(new ImageIcon(getClass().getResource("/compilador/ico2.png")).getImage());
        setLocationByPlatform(true);
        setName("ventaPP"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones"));

        compilarBoton.setText("Compilar");
        compilarBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                compilarBotonActionPerformed(evt);
            }
        });

        limpiarBoton.setText("Limpiar");
        limpiarBoton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                limpiarBotonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(compilarBoton)
                .addGap(18, 18, 18)
                .addComponent(limpiarBoton)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(limpiarBoton)
                    .addComponent(compilarBoton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Código fuente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 0, 0)));

        areaTextoEntrada.setColumns(20);
        areaTextoEntrada.setRows(5);
        areaTextoEntrada.setTabSize(4);
        areaTextoEntrada.setToolTipText("Código a compilar");
        areaTextoEntrada.setMargin(new java.awt.Insets(10, 10, 10, 10));
        jScrollPane1.setViewportView(areaTextoEntrada);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 748, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
                .addContainerGap())
        );

        jMenu1.setText("Archivo");

        abrirMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        abrirMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/compilador/abrir.png"))); // NOI18N
        abrirMenu.setText("Abrir");
        abrirMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirMenuActionPerformed(evt);
            }
        });
        jMenu1.add(abrirMenu);

        guardarMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        guardarMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/compilador/guardar.png"))); // NOI18N
        guardarMenu.setText("Guardar");
        guardarMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarMenuActionPerformed(evt);
            }
        });
        jMenu1.add(guardarMenu);

        salirMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        salirMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/compilador/cerrar.png"))); // NOI18N
        salirMenu.setText("Salir");
        salirMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirMenuActionPerformed(evt);
            }
        });
        jMenu1.add(salirMenu);

        menuBar.add(jMenu1);

        jMenu2.setText("Ayuda");

        acercaDe.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        acercaDe.setIcon(new javax.swing.ImageIcon(getClass().getResource("/compilador/acerca.png"))); // NOI18N
        acercaDe.setText("Acerca de...");
        jMenu2.add(acercaDe);

        manualUsuario.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK));
        manualUsuario.setIcon(new javax.swing.ImageIcon(getClass().getResource("/compilador/Manual.png"))); // NOI18N
        manualUsuario.setText("Manual de usuario");
        jMenu2.add(manualUsuario);

        menuBar.add(jMenu2);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void limpiarBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limpiarBotonActionPerformed
       areaTextoEntrada.setText(null);
    }//GEN-LAST:event_limpiarBotonActionPerformed

    private void compilarBotonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compilarBotonActionPerformed
      if (!areaTextoEntrada.getText().isEmpty()) 
       {
        sintactico.Compilar(areaTextoEntrada.getText());
       } 
      else 
       {
        JOptionPane.showMessageDialog(rootPane, "Introdusca codigo", "Error", JOptionPane.ERROR_MESSAGE);
       }
    }//GEN-LAST:event_compilarBotonActionPerformed

    private void salirMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirMenuActionPerformed
        System.exit(0);
    }//GEN-LAST:event_salirMenuActionPerformed

    private void abrirMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirMenuActionPerformed
      try {
                JFileChooser seleccionador = new JFileChooser(System.getProperty("user.home"));
                seleccionador.setFileFilter(new FileNameExtensionFilter("Archivo de código fuente (*.c)", "c"));
                seleccionador.setFileFilter(new FileNameExtensionFilter("Archivo de código fuente (*.cpp)", "cpp"));
                seleccionador.setFileFilter(new FileNameExtensionFilter("Archivo de texto (*.txt)", "txt"));
                seleccionador.setAcceptAllFileFilterUsed(false);
                int selecAbrir = seleccionador.showOpenDialog(rootPane);
                File archivo;
                if (selecAbrir == JFileChooser.APPROVE_OPTION) {
                    areaTextoEntrada.setText(null);
                    archivo = seleccionador.getSelectedFile();
                    try (BufferedReader lectorArchivo = new BufferedReader(new FileReader(archivo))) {
                        while (lectorArchivo.ready()) {                        
                            areaTextoEntrada.append(lectorArchivo.readLine()+System.getProperty("line.separator"));
                        }
                    }
                }
            } catch (HeadlessException | IOException ex0) {
                JOptionPane.showMessageDialog(null, "Error: " + ex0.getMessage());
            }
    }//GEN-LAST:event_abrirMenuActionPerformed

    private void guardarMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarMenuActionPerformed
       if(!areaTextoEntrada.getText().isEmpty()){
           try {
                JFileChooser seleccionador = new JFileChooser(System.getProperty("user.home"));
                seleccionador.setFileFilter(new FileNameExtensionFilter("Archivo de código fuente (*.c)", "c"));
                seleccionador.setFileFilter(new FileNameExtensionFilter("Archivo de código fuente (*.cpp)", "cpp"));
                seleccionador.setFileFilter(new FileNameExtensionFilter("Archivo de texto (*.txt)", "txt"));
                seleccionador.setAcceptAllFileFilterUsed(false);
                int selecGuardar = seleccionador.showSaveDialog(rootPane);
                FileWriter archivo;
                BufferedWriter escritor;
                String ext = ".txt";
                if (selecGuardar == JFileChooser.APPROVE_OPTION) {
                    //Se guarda la extension seleccionada y se eliminan la extension si se la puso el usuario
                    String extSel = seleccionador.getFileFilter().toString();
                    String archSel = seleccionador.getSelectedFile().toString().replaceAll(".txt", "");
                    archSel = archSel.replaceAll(".cpp", "");
                    archSel = archSel.replaceAll(".c", "");
                   //se detecta al extension y se guarda;
                    if(extSel.contains("txt")){
                        ext =".txt";
                    }
                    if(extSel.contains("cpp")){
                        ext =".cpp";
                    }
                    if(extSel.contains("txt")){
                        ext =".txt";
                    }
                    //Se crea el archivo
                    archivo = new FileWriter(archSel+ext);
                    escritor = new BufferedWriter(archivo);
                    escritor.write(areaTextoEntrada.getText());
                    escritor.close();
                    archivo.close();
                    JOptionPane.showMessageDialog(rootPane, "Se ha guradado el archivo con exito: \nEn: "+archSel+ext, "Guardado con exito", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (HeadlessException | IOException ex0) {
                JOptionPane.showMessageDialog(null, "Error: " + ex0.getMessage());
            }
       }else{
          JOptionPane.showMessageDialog(rootPane, "Error el área de texto esta vacía", "Error", JOptionPane.ERROR_MESSAGE);
       }
    }//GEN-LAST:event_guardarMenuActionPerformed

    public static void main(String args[]) 
    {
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ventanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

     java.awt.EventQueue.invokeLater(new Runnable() 
      {
       @Override
       public void run() 
        {
         new ventanaPrincipal().setVisible(true);
        }
        });
    }
    private Analisador sintactico;//Se declara el objeto Analisador
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem abrirMenu;
    private javax.swing.JMenuItem acercaDe;
    private javax.swing.JTextArea areaTextoEntrada;
    private javax.swing.JButton compilarBoton;
    private javax.swing.JMenuItem guardarMenu;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton limpiarBoton;
    private javax.swing.JMenuItem manualUsuario;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem salirMenu;
    // End of variables declaration//GEN-END:variables
}
